package com.itboye.ihomebank.activity.home;

import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.ihomebank.R;
import com.itboye.ihomebank.activity.me.ChooseAreaActivity;
import com.itboye.ihomebank.adapter.QuBean;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.bean.AvatarDataBeans;
import com.itboye.ihomebank.bean.EditBean;
import com.itboye.ihomebank.bean.QuYuBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.custom.XGridView;
import com.itboye.ihomebank.widget.photo.Bimp;
import com.itboye.ihomebank.widget.photo.CopyOfPhotoActivity;
import com.itboye.ihomebank.widget.photo.TestPicActivity;
import com.itboye.ihomebank.presenter.HousePresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.UploadImage.OnUploadlistener;
import com.itboye.ihomebank.util.XImageLoader;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 修改房源（1）
 */
public class ActivityEditHouse extends BaseOtherActivity implements Observer,
        OnUploadlistener {
    View v_statusbar;
    ImageView fabu_house_close;
    private ImageView fabu_house_img;// 大图
    private LinearLayout fabu_house_imgs;
    private ImageView fabu_house_add;// 添加图片
    private TextView fabu_house_ok;// 下一步
    private TextView fabu_house_fangshi;
    private EditText fabu_house_title, fabu_house_phone, fabu_house_people;

    private XGridView noScrollgridview;
    private GridAdapter adapter;

    RelativeLayout re_choose_city;// 选择市区
    TextView tv_city;

    List<String> list = new ArrayList<String>();

    List<QuYuBean> chengShiBean;// 城市

    // 获取市的各个区
    HousePresenter hourse;
    List<QuYuBean.Children> chengShiChildrenbean;


    private LinearLayout layout;

    /**
     * 小区
     */
    List<QuBean.Children> quBeanChildren;

    /**
     * 小区的code
     */
    private String xiaoquCode;

    List<String> listPicture = new ArrayList<String>();

    ArrayList<AvatarDataBeans> resultData;
    private String uid;
    protected StringBuffer imgBuffer;
    Intent intent;
    public static ActivityEditHouse context;
    Pattern pattern;//
    StringBuffer bufferTemp = new StringBuffer();
    private String title;
    private String phone;
    private String people;

    public static ActivityEditHouse getInstance() {
        return context;
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.fabu_house_close:
                finish();
                break;
            case R.id.fabu_house_ok:
                title = fabu_house_title.getText().toString();
                phone = fabu_house_phone.getText().toString();
                people = fabu_house_people.getText().toString();
                if (title.equals("")) {
                    ByAlert.alert("请输入标题");
                    return;
                }
                if (xiaoquCode == null) {
                    ByAlert.alert("请选择小区");
                    return;
                }
                if (phone.equals("")) {
                    ByAlert.alert("请输入联系电话");
                    return;
                }

                if (people.equals("")) {
                    ByAlert.alert("请输入联系人");
                    return;
                }
                imgBuffer = new StringBuffer();
                bufferTemp = new StringBuffer();
                uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
                List<File> files = new ArrayList<>();
                for (int i = 0; i < listImg.size(); i++) {
                    Matcher m = pattern.matcher(listImg.get(i));
                    if (!m.matches()) {
                        files.add(new File(listImg.get(i)));
                    } else {
                        bufferTemp.append(listImg.get(i) + ",");
                    }
                }
                if (files.size() <= 0 && listImg.size() <= 0) {
                    ByAlert.alert("请上传相关房源图片");
                    return;
                }
                intent = new Intent(ActivityEditHouse.this,
                        ActivityFaBuHouseTwo.class);
                intent.putExtra("title", title);
                intent.putExtra("list", (Serializable) (listImg));
//                intent.putExtra("imgIds",
//                        imgBuffer.toString());
                intent.putExtra("xiaoquCode", xiaoquCode);
                intent.putExtra("phone", phone);
                intent.putExtra("people", (SPUtils.get(ActivityEditHouse.this, null, SPContants.RealName, "") + ""));
                intent.putExtra("house_no", house_no);
                intent.putExtra("imgIds", imgBuffer.toString());
                intent.putExtra(
                        "detail",
                        SPUtils.get(ActivityEditHouse.this,
                                null,
                                SPContants.SELECT_CITY, "")
                                + xiaoQuArea);
                intent.putExtra("address", SPUtils.get(ActivityEditHouse.this, null, SPContants.SELECT_CITY, "") + "" + SPUtils.get(ActivityEditHouse.this, null, SPContants.SELECT_AREA, "") + "" + xiaoQuArea);
                intent.putExtra("model", editBean);
                startActivity(intent);


//			if (files.size() <= 0) {// 没有上传新图片
//				intent = new Intent(ActivityEditHouse.this,
//						ActivityFaBuHouseTwo.class);
//				// Bundle bundle = new Bundle();
//				intent.putExtra("title", title);
//				intent.putExtra("imgIds", bufferTemp.toString());
//				intent.putExtra("xiaoquCode", xiaoquCode);
//				intent.putExtra("phone", phone);
//				intent.putExtra("people", people);
//				intent.putExtra("house_no", house_no);
//				intent.putExtra("address", SPUtils.get(ActivityEditHouse.this, null, SPContants.SELECT_CITY, "")+""+SPUtils.get(ActivityEditHouse.this, null, SPContants.SELECT_AREA, "")+""+xiaoQuArea);
//				intent.putExtra(
//						"detail",
//						SPUtils.get(ActivityEditHouse.this, null,
//								SPContants.SELECT_CITY, "") + xiaoQuArea);
//
//				intent.putExtra("model", editBean);
//				// intent.putExtras(bundle);house_no
//				startActivity(intent);
//				return;
//			}
//			showProgressDialog("图片上传中,请稍后",false);
//			Map<String, String> params = new HashMap<String, String>();
//			params.put("uid", uid);
//			params.put("type", "house");
//
//			MultipartRequest multipartRequest = new MultipartRequest(
//					NetPublicConstant.URL
//							+ "/file/upload?client_id=by565fa4facdb191",
//					new Listener<String>() {
//
//						@Override
//						public void onResponse(String arg0) {
//							// TODO Auto-generated method stub
//							String code = "";
//							String result = "";
//							try {
//								closeProgressDialog();
//							}catch (Exception e){
//
//							}
//							closeProgressDialog();
//							try {
//								JSONObject jsonObject = new JSONObject(arg0);
//								code = jsonObject.getString("code");
//								result = jsonObject.getString("data");
//								if (code.equals("-1")) {
//									ByAlert.alert(result);
//								} else {
//									Gson gson = new Gson();
//									Type type = new TypeToken<AvatarBeans>() {
//									}.getType();
//									Log.v("msg", result + "img_ok");
//									AvatarBeans avatarBeans = gson.fromJson(
//											arg0, type);
//									imgBuffer.append(listImg);
//									for (AvatarDataBeans bean : avatarBeans
//											.getData()) {
//										imgBuffer.append(bean.getId() + ",");
//									}
//
//									intent = new Intent(ActivityEditHouse.this,
//											ActivityFaBuHouseTwo.class);
//									// Bundle bundle = new Bundle();
//									intent.putExtra("title", title);
//									intent.putExtra("imgIds",
//											imgBuffer.toString());
//									intent.putExtra("xiaoquCode", xiaoquCode);
//									intent.putExtra("phone", phone);
//									intent.putExtra("people", (SPUtils.get(ActivityEditHouse.this, null, SPContants.RealName, "") + ""));
//									intent.putExtra("house_no", house_no);
//									intent.putExtra(
//											"detail",
//											SPUtils.get(ActivityEditHouse.this,
//													null,
//													SPContants.SELECT_CITY, "")
//													+ xiaoQuArea);
//									intent.putExtra("address", SPUtils.get(ActivityEditHouse.this, null, SPContants.SELECT_CITY, "")+""+SPUtils.get(ActivityEditHouse.this, null, SPContants.SELECT_AREA, "")+""+xiaoQuArea);
//									intent.putExtra("model", editBean);
//									// intent.putExtras(bundle);
//									startActivity(intent);
//								}
//							} catch (JSONException e) {
//								// TODO Auto-generated catch block
//								e.printStackTrace();
//							}
//						}
//					}, new ErrorListener() {
//
//						@Override
//						public void onErrorResponse(VolleyError arg0) {
//							// TODO Auto-generated method stub
//							ByAlert.alert(arg0);
//						}
//					}, "image[]", files, params);
//			MyApplcation.addRequest(multipartRequest);
//			if (imgBuffer.toString().length() <= 0) {
//				// ByAlert.alert("请先");
//				return;
//			}
                break;
            case R.id.re_choose_city:// 选择市区
                intent = new Intent(this, ChooseAreaActivity.class);
                startActivityForResult(intent, 101);
                break;
            default:
                break;
        }
    }

    public void guanbi() {
        finish();
    }


    private String house_no;
    private HousePresenter housePresenter;


    @Override
    protected int layout_id() {
        return R.layout.activity_fabu_house;
    }

    @Override
    protected void onInitController() {
        pattern = Pattern.compile("^[0-9]*$");
        uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
        house_no = getIntent().getStringExtra("house_no");
        if (house_no == null) {// 发布房源

        } else {// 修改房源
            housePresenter = new HousePresenter(this);
            housePresenter.houseEdit(uid, house_no);
        }
        fabu_house_phone.setEnabled(false);
        fabu_house_phone.setText(SPUtils.get(this, null, SPContants.MOBILE, "")
                + "");
        String sex = "";
        if ((SPUtils.get(this, null, SPContants.SEX, "") + "").equals("0")) {// 保密
            int length = (SPUtils.get(this, null, SPContants.RealName, "") + "")
                    .length();
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < length - 1; i++) {
                sex += "*";
            }

        } else if ((SPUtils.get(this, null, SPContants.SEX, "") + "")
                .equals("1")) {//
            sex = "女士";
        } else if ((SPUtils.get(this, null, SPContants.SEX, "") + "")
                .equals("2")) {
            sex = "先生";
        }
        fabu_house_people.setEnabled(false);
        fabu_house_people.setText((SPUtils.get(this, null, SPContants.RealName,
                "") + "").charAt(0) + sex);
        noScrollgridview = (XGridView) findViewById(R.id.noScrollgridview);
        noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));

        noScrollgridview.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                if (arg2 == listImg.size()) {
                    new PopupWindows(ActivityEditHouse.this, noScrollgridview);
                } else {
                    Intent intent = new Intent(ActivityEditHouse.this,
                            CopyOfPhotoActivity.class);
                    intent.putExtra("ID", arg2);
                    intent.putExtra("type", 0);
                    startActivityForResult(intent, 101);
                }
            }
        });
        noScrollgridview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                listImg.add(0, listImg.get(position));
                listImg.remove(position+1);
                try {
                    XImageLoader
                            .load(NetPublicConstant.IMAGE_URL
                                    + listImg.get(0), fabu_house_img);
                } catch (Exception e) {
                    // TODO: handle exception
                    XImageLoader.load("file://" + listImg.get(0), fabu_house_img);
                }
                adapter.notifyDataSetChanged();
                return true;
            }
        });
    }

    TextView fabu_house_v;

    @Override
    protected void onInit() {
        setStatusBarHeight(v_statusbar);
        context = this;
        hourse = new HousePresenter(this);
        fabu_house_v.setVisibility(View.GONE);
    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    private static final int TAKE_PICTURE_FANG_YUAN = 001;
    private String path = "";
    private String xiaoQuArea;
    private EditBean editBean;
    public static List<String> listImg = new ArrayList<>();

    public void photo() {
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(Environment.getExternalStorageDirectory()
                + "/myimage/", String.valueOf(System.currentTimeMillis())
                + ".jpg");
        path = file.getPath();
        Uri imageUri = Uri.fromFile(file);
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(openCameraIntent, TAKE_PICTURE_FANG_YUAN);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PICTURE_FANG_YUAN:
                if (Bimp.drr.size() < 9 && resultCode == -1) {
                    // Bimp.drr.add(path);
                    listImg.add(path);
                    adapter.notifyDataSetChanged();
                }
                break;

        }
        if (requestCode == 101 && resultCode == 102) {
            fabu_house_img.setImageResource(R.drawable.wutu);
        }
        if (requestCode == 101 && resultCode == 103) {
            // fabu_house_img.setImageBitmap(Bimp.bmp.get(Bimp.bmp.size() - 1));
        }
        if (requestCode == 101 && resultCode == 104) {
            if (data != null) {
                xiaoquCode = data.getStringExtra("xiaoqu");
                xiaoQuArea = data.getStringExtra("xiaoquName");
                tv_city.setText(xiaoQuArea);
            }
        }
    }

    protected void onRestart() {
        adapter = new GridAdapter(this);
        noScrollgridview.setAdapter(adapter);
        if (listImg.size() > 0){
            try {
                XImageLoader
                        .load(NetPublicConstant.IMAGE_URL
                                + listImg.get(0), fabu_house_img);
            } catch (Exception e) {
                // TODO: handle exception
                XImageLoader.load("file://" + listImg.get(0), fabu_house_img);
            }
        }else{
            fabu_house_img.setImageResource(R.drawable.wutu);
        }
        super.onRestart();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        listImg.clear();
        // Bimp.bmp.remove(TAKE_PICTURE);
    }

    public class PopupWindows extends PopupWindow {

        public PopupWindows(Context mContext, View parent) {

            View view = View
                    .inflate(mContext, R.layout.item_popupwindows, null);
            view.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.fade_ins));
            LinearLayout ll_popup = (LinearLayout) view
                    .findViewById(R.id.ll_popup);
            ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.push_bottom_in_2));

            setWidth(LayoutParams.FILL_PARENT);
            setHeight(LayoutParams.FILL_PARENT);
            setBackgroundDrawable(new BitmapDrawable());
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            update();

            Button bt1 = (Button) view
                    .findViewById(R.id.item_popupwindows_camera);
            Button bt2 = (Button) view
                    .findViewById(R.id.item_popupwindows_Photo);
            Button bt3 = (Button) view
                    .findViewById(R.id.item_popupwindows_cancel);
            bt1.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    photo();
                    dismiss();
                }
            });
            bt2.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    Intent intent = new Intent(ActivityEditHouse.this,
                            TestPicActivity.class);
                    intent.putExtra("max", 9);
                    startActivity(intent);
                    dismiss();
                }
            });
            bt3.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    dismiss();
                }
            });

        }
    }


    public class GridAdapter extends BaseAdapter {
        private LayoutInflater inflater; // 视图容器
        private int selectedPosition = -1;// 选中的位置
        private boolean shape;

        public boolean isShape() {
            return shape;
        }

        public void setShape(boolean shape) {
            this.shape = shape;
        }

        public GridAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        public int getCount() {
            return (listImg.size() + 1);
        }

        public Object getItem(int arg0) {

            return null;
        }

        public long getItemId(int arg0) {

            return 0;
        }

        public void setSelectedPosition(int position) {
            selectedPosition = position;
        }

        public int getSelectedPosition() {
            return selectedPosition;
        }

        /**
         * ListView Item设置
         */
        public View getView(int position, View convertView, ViewGroup parent) {
            final int coord = position;
            ViewHolder holder = null;
            if (convertView == null) {

                convertView = inflater.inflate(R.layout.item_published_grida,
                        parent, false);
                holder = new ViewHolder();
                holder.image = (ImageView) convertView
                        .findViewById(R.id.item_grida_image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            if (position == listImg.size()) {
                holder.image.setImageBitmap(BitmapFactory.decodeResource(
                        getResources(), R.drawable.icon_addpic_unfocused));

                if (position == 9) {
                    holder.image.setVisibility(View.GONE);
                }
            } else {
                try {
                    Integer.parseInt(listImg.get(position));
                    XImageLoader
                            .load(NetPublicConstant.IMAGE_URL
                                    + listImg.get(position), holder.image);
                } catch (Exception e) {
                    // TODO: handle exception
                    XImageLoader.load("file://" + listImg.get(position),
                            holder.image);
                }
                // holder.image.setImageBitmap(listImg.get(position));
            }

            return convertView;
        }

        public class ViewHolder {
            public ImageView image;
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType() == HousePresenter.houseEdit_success) {
                editBean = (EditBean) entity.getData();
                listImg = editBean.getShowImgs();
                adapter = new GridAdapter(this);
                noScrollgridview.setAdapter(adapter);
                if (listImg.size() > 0) {
                    XImageLoader.load(NetPublicConstant.IMAGE_URL + listImg.get(listImg.size() - 1), fabu_house_img);
                }
                fabu_house_title.setText(editBean.getTitle());
                xiaoquCode = editBean.getCommunity();
                title = editBean.getTitle();
                tv_city.setText(editBean.getCommunityName());

                fabu_house_phone.setText(editBean.getContactPhone());

            }
            if (entity.getEventType() == HousePresenter.houseEdit_fail) {
                ByAlert.alert(entity.getData());
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {

        }
    }


    @Override
    public void OnSuccess(ArrayList<AvatarDataBeans> resultData) {

        AvatarDataBeans bean = new AvatarDataBeans();
        for (int i = 0; i < resultData.size(); i++) {
            bean.setId(resultData.get(i).getId());

            listPicture.add(resultData.get(i).getId());
        }
    }

    @Override
    public void OnError(String resultData) {
        ByAlert.alert("上传失败");

    }

}
